package com.hospital.controller;

import com.hospital.common.Result;
import com.hospital.common.UserRole;
import com.hospital.entity.*;
import com.hospital.service.*;
import com.hospital.mapper.AnnouncementMapper;
import com.hospital.util.UserContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.Random;
import java.util.Formatter;
import java.util.stream.Collectors;

/**
 * 业务控制器（医生和管理员共用）
 *
 * @author Hospital Management System
 */
@Slf4j
@Api(tags = "业务管理（医生和管理员共用）")
@RestController
@RequestMapping("/business")
@RequiredArgsConstructor
public class BusinessController {

    private final UserService userService;
    private final DepartmentService departmentService;
    private final RegistrationService registrationService;
    private final MedicalRecordService medicalRecordService;
    private final PrescriptionService prescriptionService;
    private final PrescriptionDetailService prescriptionDetailService;
    private final WardService wardService;
    private final ScheduleService scheduleService;
    private final MedicineService medicineService;
    private final AnnouncementMapper announcementMapper;
    private final ObjectMapper objectMapper;

    // ==================== 科室信息查询 ====================
    
    @ApiOperation("获取所有科室列表")
    @GetMapping("/departments")
    public Result<Object> getDepartments(
            @ApiParam("科室名称") @RequestParam(required = false) String name,
            @ApiParam("科室编码") @RequestParam(required = false) String code,
            @ApiParam("状态") @RequestParam(required = false) Integer status,
            @ApiParam("页码") @RequestParam(required = false) Integer page,
            @ApiParam("每页大小") @RequestParam(required = false) Integer size,
            @ApiParam("是否返回树形结构") @RequestParam(required = false, defaultValue = "false") Boolean tree) {
        
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        // 医生和管理员都可以查看科室列表
     
            
            // 根据tree参数决定返回树形结构还是分页列表
            if (tree) {
                List<Map<String, Object>> treeData = departmentService.getDepartmentTree(name, code, status);
                return Result.success(treeData);
            } else {
                Map<String, Object> result = departmentService.getDepartmentsWithPagination(
                    name, code, status, page != null ? page : 1, size != null ? size : 20);
                return Result.success(result);
            }
      
    }

    @ApiOperation("根据科室ID获取医生列表")
    @GetMapping("/department/{departmentId}/doctors")
    public Result<List<User>> getDoctorsByDepartment(@PathVariable Long departmentId) {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        List<User> doctors = userService.getDoctorsByDepartment(departmentId);
        return Result.success(doctors);
    }

    // ==================== 挂号信息管理 ====================
    
    @ApiOperation("获取挂号列表")
    @GetMapping("/registrations")
    public Result<Map<String, Object>> getRegistrations(
            @ApiParam("搜索关键词") @RequestParam(required = false) String keyword,
            @ApiParam("状态") @RequestParam(required = false) Integer status,
            @ApiParam("类型") @RequestParam(required = false) Integer type,
            @ApiParam("预约日期") @RequestParam(required = false) String appointmentDate,
            @ApiParam("科室ID") @RequestParam(required = false) Long departmentId,
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "20") Integer size) {
        
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        // 转换日期参数
        LocalDate date = null;
        if (StringUtils.hasText(appointmentDate)) {
            try {
                date = LocalDate.parse(appointmentDate);
            } catch (Exception e) {
                log.warn("日期格式错误: {}", appointmentDate);
                return Result.error("日期格式错误");
            }
        }
        
        log.info("接收到挂号列表查询请求 - keyword: {}, status: {}, type: {}, appointmentDate: {}, departmentId: {}, page: {}, size: {}", 
                 keyword, status, type, appointmentDate, departmentId, page, size);
        
        if (UserRole.DOCTOR.equals(currentUser.getRole())) {
            // 医生只能查看自己的挂号信息
            List<Registration> registrations = registrationService.getDoctorRegistrations(appointmentDate);
            Map<String, Object> result = new HashMap<>();
            result.put("list", registrations);
            result.put("total", registrations.size());
            result.put("page", 1);
            result.put("size", registrations.size());
            result.put("pages", 1);
            return Result.success(result);
        } else if (!UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足");
        }
        
        // 管理员可以查看所有挂号信息
        Map<String, Object> result = registrationService.getRegistrations(
            keyword, status, type, date, departmentId, page, size);
        
        log.info("查询结果 - total: {}", result.get("total"));
        return Result.success(result);
    }

    @ApiOperation("获取挂号详情")
    @GetMapping("/registration/{registrationId}")
    public Result<Registration> getRegistrationDetail(@PathVariable Long registrationId) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            Registration registration = registrationService.getById(registrationId);
            if (registration != null) {
                // 填充关联信息
                registrationService.fillRelatedInfo(Arrays.asList(registration));
            }
            return Result.success(registration);
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("更新挂号状态")
    @PutMapping("/registration/{registrationId}/status")
    public Result<Void> updateRegistrationStatus(
            @PathVariable Long registrationId,
            @RequestBody Map<String, Object> request) {
        
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        if (!UserRole.DOCTOR.equals(currentUser.getRole()) && 
            !UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足");
        }
        
        try {
            // 获取参数
            Integer status = (Integer) request.get("status");
            String remark = (String) request.get("remark");
            
            // 参数校验
            if (status == null) {
                return Result.error("状态不能为空");
            }
            if (remark == null || remark.trim().isEmpty()) {
                return Result.error("备注不能为空");
            }
            
            // 获取当前挂号信息
            Registration registration = registrationService.getById(registrationId);
            if (registration == null) {
                return Result.error("挂号记录不存在");
            }
            
            // 状态检查
            if (registration.getStatus() == 2) {
                return Result.error("已取消的挂号不能更改状态");
            }
            if (registration.getStatus() == 3) {
                return Result.error("已完成的挂号不能更改状态");
            }
            
            // 医生只能处理自己科室的挂号
            if (UserRole.DOCTOR.equals(currentUser.getRole())) {
                User doctor = userService.getById(currentUser.getId());
                if (!registration.getDepartmentId().equals(doctor.getDepartmentId())) {
                    return Result.error("只能处理本科室的挂号");
                }
            }
            
            // 更新状态
            registration.setStatus(status);
            registration.setRemark(remark);
            registration.setUpdateTime(LocalDateTime.now());
            
            // 如果是确认就诊，记录就诊时间
            if (status == 1) {
                registration.setVisitTime(LocalDateTime.now());
            }
            // 如果是完成就诊，记录完成时间并创建就诊记录
            else if (status == 3) {
                registration.setFinishTime(LocalDateTime.now());
                
                // 创建就诊记录
                MedicalRecord medicalRecord = new MedicalRecord();
                medicalRecord.setRegistrationId(registrationId);
                medicalRecord.setUserId(registration.getUserId());
                medicalRecord.setUserName(registration.getUserName());
                medicalRecord.setDoctorId(registration.getDoctorId());
                medicalRecord.setDoctorName(registration.getDoctorName());
                medicalRecord.setDepartmentId(registration.getDepartmentId());
                medicalRecord.setDepartmentName(registration.getDepartmentName());
                medicalRecord.setVisitTime(registration.getVisitTime());
                medicalRecord.setStatus(0); // 设置为草稿状态
                medicalRecord.setRemark(remark);
                medicalRecord.setCreateTime(LocalDateTime.now());
                medicalRecord.setUpdateTime(LocalDateTime.now());
                medicalRecord.setDeleted(0);
                
                // 保存就诊记录
                medicalRecordService.save(medicalRecord);
            }
            
            registrationService.updateById(registration);
            
            return Result.success(null, "状态更新成功");
            
        } catch (Exception e) {
            log.error("更新挂号状态失败", e);
            return Result.error("更新挂号状态失败: " + e.getMessage());
        }
    }

    @ApiOperation("获取我的挂号记录")
    @GetMapping("/my-registrations")
    public Result<List<Registration>> getMyRegistrations() {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        List<Registration> registrations = registrationService.getUserRegistrations();
        // 填充关联信息
        if (registrations != null && !registrations.isEmpty()) {
            registrationService.fillRelatedInfo(registrations);
        }
        return Result.success(registrations);
    }

    @ApiOperation("取消挂号")
    @PostMapping("/registration/{registrationId}/cancel")
    public Result<Void> cancelRegistration(@PathVariable Long registrationId) {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        registrationService.cancelRegistration(registrationId);
        return Result.success();
    }

    @ApiOperation("预约挂号")
    @PostMapping("/registration")
    public Result<Void> makeAppointment(@Validated @RequestBody Registration registration) {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        // 设置患者ID
        registration.setUserId(currentUser.getId());
        registrationService.makeAppointment(registration);
        return Result.success();
    }

    // ==================== 排班信息管理 ====================
    
    @ApiOperation("获取排班列表")
    @GetMapping("/schedules")
    public Result<?> getSchedules(
            @ApiParam("开始日期") @RequestParam(required = false) String startDate,
            @ApiParam("结束日期") @RequestParam(required = false) String endDate,
            @ApiParam("科室ID") @RequestParam(required = false) Long departmentId,
            @ApiParam("状态") @RequestParam(required = false) Integer status,
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "20") Integer size,
            @ApiParam("单个日期查询") @RequestParam(required = false) String date) {
        
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }

        // 如果是用户查询单个日期的排班
        if (UserRole.PATIENT.equals(currentUser.getRole()) && date != null && departmentId != null) {
            LocalDate scheduleDate = LocalDate.parse(date);
            return Result.success(scheduleService.getSchedulesByDateAndDepartment(scheduleDate, departmentId));
        }
        
        // 原有的医生和管理员查询逻辑
        if (UserRole.DOCTOR.equals(currentUser.getRole())) {
            // 医生查看自己的排班 - 如果没有提供日期，默认查看未来30天
            LocalDate doctorStart = startDate != null ? LocalDate.parse(startDate) : LocalDate.now();
            LocalDate doctorEnd = endDate != null ? LocalDate.parse(endDate) : LocalDate.now().plusDays(30);
            
            List<Schedule> schedules = scheduleService.getDoctorSchedules(currentUser.getId(), doctorStart, doctorEnd);
            Map<String, Object> result = new HashMap<>();
            result.put("list", schedules);
            result.put("total", schedules.size());
            result.put("page", page);
            result.put("size", size);
            result.put("pages", (schedules.size() + size - 1) / size);
            return Result.success(result);
        } else if (UserRole.ADMIN.equals(currentUser.getRole())) {
            // 管理员查看全院排班 - 使用分页，如果没有日期参数则查询全部
            LocalDate start = startDate != null ? LocalDate.parse(startDate) : null;
            LocalDate end = endDate != null ? LocalDate.parse(endDate) : null;
            Map<String, Object> schedules = scheduleService.getSchedulesWithPagination(
                departmentId, status, start, end, page, size);
            return Result.success(schedules);
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("获取排班详情")
    @GetMapping("/schedule/{scheduleId}")
    public Result<Schedule> getScheduleDetail(@PathVariable Long scheduleId) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            Schedule schedule = scheduleService.getById(scheduleId);
            return Result.success(schedule);
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("更新排班状态")
    @PutMapping("/schedule/{scheduleId}/status")
    public Result<Void> updateScheduleStatus(
            @PathVariable Long scheduleId,
            @ApiParam("状态") @RequestParam Integer status,
            @ApiParam("备注") @RequestParam(required = false) String remark) {
        
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            scheduleService.updateScheduleStatus(scheduleId, status, remark);
            return Result.success(null, "排班状态更新成功");
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("创建排班")
    @PostMapping("/schedule")
    public Result<Void> createSchedule(@Validated @RequestBody Schedule schedule) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.ADMIN.equals(currentUser.getRole())) {
            scheduleService.createSchedule(schedule);
            return Result.success(null, "排班创建成功");
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("更新排班")
    @PutMapping("/schedule")
    public Result<Void> updateSchedule(@Validated @RequestBody Schedule schedule) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.ADMIN.equals(currentUser.getRole())) {
            scheduleService.updateSchedule(schedule);
            return Result.success(null, "排班更新成功");
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("删除排班")
    @DeleteMapping("/schedule/{scheduleId}")
    public Result<Void> deleteSchedule(@PathVariable Long scheduleId) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.ADMIN.equals(currentUser.getRole())) {
            scheduleService.deleteSchedule(scheduleId);
            return Result.success(null, "排班删除成功");
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("获取排班统计")
    @GetMapping("/schedule/statistics")
    public Result<Map<String, Object>> getScheduleStatistics(
            @ApiParam("开始日期") @RequestParam(required = false) String startDate,
            @ApiParam("结束日期") @RequestParam(required = false) String endDate) {
        
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.ADMIN.equals(currentUser.getRole())) {
            LocalDate start = startDate != null ? LocalDate.parse(startDate) : LocalDate.now().minusDays(30);
            LocalDate end = endDate != null ? LocalDate.parse(endDate) : LocalDate.now();
            
            Map<String, Object> statistics = scheduleService.getScheduleStatistics(start, end);
            return Result.success(statistics);
        }
        
        return Result.error("权限不足");
    }

    // ==================== 就诊记录管理 ====================
    
    @ApiOperation("获取我的就诊记录")
    @GetMapping("/my-medical-records")
    public Result<List<MedicalRecord>> getMyMedicalRecords() {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        List<MedicalRecord> records = medicalRecordService.getUserMedicalRecords(currentUser.getId());
        // 填充关联信息
        if (records != null && !records.isEmpty()) {
            medicalRecordService.fillRelatedInfo(records);
        }
        return Result.success(records);
    }

    @ApiOperation("获取就诊记录列表")
    @GetMapping("/medical-records")
    public Result<Map<String, Object>> getMedicalRecords(
            @ApiParam("患者姓名") @RequestParam(required = false) String patientName,
            @ApiParam("医生姓名") @RequestParam(required = false) String doctorName,
            @ApiParam("状态") @RequestParam(required = false) Integer status,
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "20") Integer size) {
        
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        if (UserRole.DOCTOR.equals(currentUser.getRole())) {
            // 医生只能查看自己的就诊记录
            Map<String, Object> records = medicalRecordService.getDoctorMedicalRecordsWithPagination(
                currentUser.getId(), patientName, status, page, size);
            return Result.success(records);
        } else if (!UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足");
        }
        
        // 管理员可以查看所有就诊记录
        Map<String, Object> records = medicalRecordService.getMedicalRecordsWithPagination(
            patientName, doctorName, status, page, size);
        return Result.success(records);
    }

    @ApiOperation("获取就诊记录详情")
    @GetMapping("/medical-record/{recordId}")
    public Result<Map<String, Object>> getMedicalRecordDetail(@PathVariable Long recordId) {
        User currentUser = UserContext.getCurrentUser();
        MedicalRecord record = medicalRecordService.getById(recordId);
        
        if (record == null) {
            return Result.error("就诊记录不存在");
        }

        // 填充关联信息
        medicalRecordService.fillRelatedInfo(record);

        // 获取处方信息
        List<Prescription> prescriptions = prescriptionService.getByMedicalRecordId(recordId);
        if (prescriptions != null && !prescriptions.isEmpty()) {
            // 填充处方明细
            prescriptions.forEach(prescription -> {
                List<PrescriptionDetail> details = prescriptionDetailService.getByPrescriptionId(prescription.getId());
                prescription.setPrescriptionDetails(details);
            });
        }

        // 构建返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("record", record);
        data.put("prescriptions", prescriptions);

        // 如果需要住院，添加住院信息
        if (Boolean.TRUE.equals(record.getNeedHospitalization())) {
            Map<String, Object> hospitalizationInfo = new HashMap<>();
            hospitalizationInfo.put("wardId", record.getWardId());
            hospitalizationInfo.put("wardName", record.getWardName());
            hospitalizationInfo.put("bedNumber", record.getBedNumber());
            hospitalizationInfo.put("estimatedDays", record.getEstimatedDays());
            hospitalizationInfo.put("status", record.getHospitalizationStatus());
            hospitalizationInfo.put("admissionTime", record.getAdmissionTime());
            hospitalizationInfo.put("estimatedDischargeTime", record.getEstimatedDischargeTime());
            hospitalizationInfo.put("actualDischargeTime", record.getActualDischargeTime());
            data.put("hospitalizationInfo", hospitalizationInfo);
        }

        return Result.success(data);
    }

    @ApiOperation("添加就诊记录")
    @PostMapping("/medical-record")
    public Result<Void> addMedicalRecord(@Validated @RequestBody MedicalRecord medicalRecord) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole())) {
            medicalRecord.setDoctorId(currentUser.getId());
            medicalRecordService.save(medicalRecord);
            return Result.success(null, "就诊记录添加成功");
        }
        
        return Result.error("权限不足，仅医生可添加就诊记录");
    }

    @ApiOperation("更新就诊记录")
    @PutMapping("/medical-record")
    public Result<Void> updateMedicalRecord(@Validated @RequestBody MedicalRecord medicalRecord) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            
            // 获取原记录状态
            MedicalRecord oldRecord = medicalRecordService.getById(medicalRecord.getId());
            if (oldRecord == null) {
                return Result.error("就诊记录不存在");
            }
            
            // 更新就诊记录
            medicalRecordService.updateById(medicalRecord);
            
            // 如果状态从非完成变为完成，创建处方记录
            if (oldRecord.getStatus() != 1 && medicalRecord.getStatus() == 1) {
                try {
                    // 创建处方记录
                    Prescription prescription = new Prescription();
                    prescription.setMedicalRecordId(medicalRecord.getId());
                    prescription.setUserId(medicalRecord.getUserId());
                    prescription.setDoctorId(medicalRecord.getDoctorId());
                    prescription.setDepartmentId(medicalRecord.getDepartmentId());
                    prescription.setType(1); // 默认为西药处方
                    prescription.setStatus(0); // 待审核状态
                    prescription.setPrescribeTime(LocalDateTime.now());
                    prescription.setCreateTime(LocalDateTime.now());
                    prescription.setUpdateTime(LocalDateTime.now());
                    prescription.setDeleted(0);
                    prescription.setRemark("由就诊记录自动生成");
                    
                    // 生成处方编号：PRE + 年月日 + 6位随机数
                    String prescriptionNo = "PRE" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                            + String.format("%06d", new Random().nextInt(999999));
                    prescription.setPrescriptionNo(prescriptionNo);
                    
                    // 保存处方记录
                    prescriptionService.save(prescription);
                    log.info("就诊记录完成，自动创建处方记录，处方编号：{}", prescriptionNo);
                } catch (Exception e) {
                    log.error("创建处方记录失败", e);
                    return Result.error("就诊记录更新成功，但创建处方记录失败：" + e.getMessage());
                }
            }
            
            return Result.success(null, "就诊记录更新成功");
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("删除就诊记录")
    @DeleteMapping("/medical-record/{recordId}")
    public Result<Void> deleteMedicalRecord(@PathVariable Long recordId) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            medicalRecordService.removeById(recordId);
            return Result.success(null, "就诊记录删除成功");
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("分配病房床位")
    @PostMapping("/medical-record/{recordId}/assign-bed")
    public Result<Void> assignBed(
            @PathVariable Long recordId,
            @RequestBody Map<String, Object> request) {
        User currentUser = UserContext.getCurrentUser();
        if (!UserRole.DOCTOR.equals(currentUser.getRole()) && 
            !UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足");
        }

        try {
            Long wardId = Long.valueOf(request.get("wardId").toString());
            Integer bedNumber = Integer.valueOf(request.get("bedNumber").toString());
            Integer estimatedDays = Integer.valueOf(request.get("estimatedDays").toString());

            boolean success = medicalRecordService.assignBed(recordId, wardId, bedNumber, estimatedDays);
            return success ? Result.success(null, "床位分配成功") : Result.error("床位分配失败");
        } catch (Exception e) {
            return Result.error("床位分配失败: " + e.getMessage());
        }
    }

    @ApiOperation("获取病房可用床位")
    @GetMapping("/ward/{wardId}/available-beds")
    public Result<List<Integer>> getAvailableBeds(@PathVariable Long wardId) {
        User currentUser = UserContext.getCurrentUser();
        if (!UserRole.DOCTOR.equals(currentUser.getRole()) && 
            !UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足");
        }

        try {
            List<Integer> availableBeds = medicalRecordService.getAvailableBeds(wardId);
            return Result.success(availableBeds);
        } catch (Exception e) {
            return Result.error("获取可用床位失败: " + e.getMessage());
        }
    }

    @ApiOperation("办理入院")
    @PostMapping("/medical-record/{recordId}/admission")
    public Result<Void> admission(@PathVariable Long recordId) {
        User currentUser = UserContext.getCurrentUser();
        if (!UserRole.DOCTOR.equals(currentUser.getRole()) && 
            !UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足");
        }

        try {
            boolean success = medicalRecordService.admission(recordId);
            return success ? Result.success(null, "入院办理成功") : Result.error("入院办理失败");
        } catch (Exception e) {
            return Result.error("入院办理失败: " + e.getMessage());
        }
    }

    @ApiOperation("办理出院")
    @PostMapping("/medical-record/{recordId}/discharge")
    public Result<Void> discharge(@PathVariable Long recordId) {
        User currentUser = UserContext.getCurrentUser();
        if (!UserRole.DOCTOR.equals(currentUser.getRole()) && 
            !UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足");
        }

        try {
            boolean success = medicalRecordService.discharge(recordId);
            return success ? Result.success(null, "出院办理成功") : Result.error("出院办理失败");
        } catch (Exception e) {
            return Result.error("出院办理失败: " + e.getMessage());
        }
    }

    // ==================== 处方信息管理 ====================
    
    @ApiOperation("获取处方列表")
    @GetMapping("/prescriptions")
    public Result<Map<String, Object>> getPrescriptions(
            @ApiParam("患者姓名") @RequestParam(required = false) String patientName,
            @ApiParam("处方编号") @RequestParam(required = false) String prescriptionNo,
            @ApiParam("处方状态") @RequestParam(required = false) Integer status,
            @ApiParam("处方类型") @RequestParam(required = false) Integer type,
            @ApiParam("开具日期") @RequestParam(required = false) String prescribeDate,
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "20") Integer size) {
        
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        Map<String, Object> prescriptions;
        
        if (UserRole.DOCTOR.equals(currentUser.getRole())) {
            // 医生只能查看自己的处方
            prescriptions = prescriptionService.getDoctorPrescriptionsWithPagination(
                currentUser.getId(), patientName, prescriptionNo, status, type, prescribeDate, page, size);
        } else if (UserRole.ADMIN.equals(currentUser.getRole())) {
            // 管理员可以查看所有处方
            prescriptions = prescriptionService.getPrescriptionsWithPagination(
                patientName, prescriptionNo, status, type, prescribeDate, page, size);
        } else {
            return Result.error("权限不足");
        }
        
        return Result.success(prescriptions);
    }

    @ApiOperation("添加处方")
    @PostMapping("/prescription")
    public Result<Void> addPrescription(@Validated @RequestBody Prescription prescription) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole())) {
            // 从数据库获取完整的医生信息（包含department_id）
            User doctorInfo = userService.getById(currentUser.getId());
            if (doctorInfo == null) {
                return Result.error("医生信息不存在");
            }
            
            // 检查医生是否设置了科室信息
            if (doctorInfo.getDepartmentId() == null) {
                return Result.error("医生信息不完整，缺少科室信息，请联系管理员");
            }
            
            // 检查处方明细
            if ((prescription.getType() == 1 || prescription.getType() == 2) 
                && (prescription.getPrescriptionDetails() == null 
                || prescription.getPrescriptionDetails().isEmpty())) {
                return Result.error("处方类型为药品时，必须添加处方明细");
            }
            
            // 设置医生信息
            prescription.setDoctorId(doctorInfo.getId());
            // 设置科室信息
            prescription.setDepartmentId(doctorInfo.getDepartmentId());
            // 强制设置状态为待审核
            prescription.setStatus(0);
            // 设置开具时间
            prescription.setPrescribeTime(LocalDateTime.now());
            // 设置创建和更新时间
            prescription.setCreateTime(LocalDateTime.now());
            prescription.setUpdateTime(LocalDateTime.now());
            // 设置删除标记
            prescription.setDeleted(0);
            
            try {
                boolean success = prescriptionService.save(prescription);
                if (success) {
                    return Result.success(null, "处方添加成功");
                } else {
                    return Result.error("处方添加失败");
                }
            } catch (Exception e) {
                log.error("添加处方失败", e);
                return Result.error("添加处方失败：" + e.getMessage());
            }
        }
        
        return Result.error("权限不足，仅医生可添加处方");
    }

    @ApiOperation("更新处方")
    @PutMapping("/prescription")
    public Result<Void> updatePrescription(@Validated @RequestBody Prescription prescription) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            
            // 获取原处方信息
            Prescription oldPrescription = prescriptionService.getById(prescription.getId());
            if (oldPrescription == null) {
                return Result.error("处方不存在");
            }
            
            // 检查权限（医生只能修改自己的处方）
            if (UserRole.DOCTOR.equals(currentUser.getRole()) 
                && !currentUser.getId().equals(oldPrescription.getDoctorId())) {
                return Result.error("只能修改自己开具的处方");
            }
            
            // 检查状态（只能修改待审核的处方）
            if (oldPrescription.getStatus() != 0) {
                return Result.error("只能修改待审核的处方");
            }
            
            // 检查处方明细
            if ((prescription.getType() == 1 || prescription.getType() == 2) 
                && (prescription.getPrescriptionDetails() == null 
                || prescription.getPrescriptionDetails().isEmpty())) {
                return Result.error("处方类型为药品时，必须添加处方明细");
            }
            
            try {
                boolean success = prescriptionService.updateById(prescription);
                if (success) {
                    return Result.success(null, "处方更新成功");
                } else {
                    return Result.error("处方更新失败");
                }
            } catch (Exception e) {
                log.error("更新处方失败", e);
                return Result.error("更新处方失败：" + e.getMessage());
            }
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("审核处方")
    @PutMapping("/prescription/review")
    public Result<Void> reviewPrescription(@RequestBody Map<String, Object> request) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            Long prescriptionId = Long.valueOf(request.get("prescriptionId").toString());
            prescriptionService.reviewPrescription(prescriptionId, currentUser.getId());
            return Result.success(null, "处方审核成功");
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("配药")
    @PutMapping("/prescription/dispense")
    public Result<Void> dispensePrescription(@RequestBody Map<String, Object> request) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            Long prescriptionId = Long.valueOf(request.get("prescriptionId").toString());
            prescriptionService.dispensePrescription(prescriptionId, currentUser.getId());
            return Result.success(null, "配药成功");
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("获取处方详情")
    @GetMapping("/prescription/{prescriptionId}")
    public Result<Prescription> getPrescriptionDetail(@PathVariable Long prescriptionId) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            try {
                Prescription prescription = prescriptionService.getPrescriptionDetail(prescriptionId);
                if (prescription == null) {
                    return Result.error("处方不存在");
                }
                return Result.success(prescription);
            } catch (Exception e) {
                log.error("获取处方详情失败", e);
                return Result.error("获取处方详情失败：" + e.getMessage());
            }
        }
        
        return Result.error("权限不足");
    }

    // ==================== 药品库存管理 ====================
    
    @ApiOperation("获取药品列表")
    @GetMapping("/medicines")
    public Result<Map<String, Object>> getMedicines(
            @ApiParam("搜索关键词") @RequestParam(required = false) String keyword,
            @ApiParam("药品分类") @RequestParam(required = false) Integer category,
            @ApiParam("药品ID列表") @RequestParam(required = false) String ids,
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "20") Integer size) {
        
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            
            Map<String, Object> medicines = medicineService.getMedicinesWithPagination(
                keyword, category, ids, page, size);
            return Result.success(medicines);
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("获取药品详情")
    @GetMapping("/medicine/{medicineId}")
    public Result<Medicine> getMedicineDetail(@PathVariable Long medicineId) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            Medicine medicine = medicineService.getById(medicineId);
            return Result.success(medicine);
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("获取库存不足的药品")
    @GetMapping("/medicines/low-stock")
    public Result<List<Medicine>> getLowStockMedicines() {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            List<Medicine> medicines = medicineService.getLowStockMedicines();
            return Result.success(medicines);
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("获取即将过期的药品")
    @GetMapping("/medicines/near-expiry")
    public Result<List<Medicine>> getNearExpiryMedicines() {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            List<Medicine> medicines = medicineService.getNearExpiryMedicines();
            return Result.success(medicines);
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("获取已过期的药品")
    @GetMapping("/medicines/expired")
    public Result<List<Medicine>> getExpiredMedicines() {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.ADMIN.equals(currentUser.getRole())) {
            List<Medicine> medicines = medicineService.getExpiredMedicines();
            return Result.success(medicines);
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("药品入库")
    @PostMapping("/medicine/{medicineId}/add-stock")
    public Result<Void> addMedicineStock(
            @PathVariable Long medicineId,
            @ApiParam("入库数量") @RequestParam Integer quantity,
            @ApiParam("备注") @RequestParam(required = false) String remark) {
        
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.ADMIN.equals(currentUser.getRole())) {
            medicineService.addStock(medicineId, quantity, remark);
            return Result.success(null, "药品入库成功");
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("药品出库")
    @PostMapping("/medicine/{medicineId}/reduce-stock")
    public Result<Void> reduceMedicineStock(
            @PathVariable Long medicineId,
            @ApiParam("出库数量") @RequestParam Integer quantity,
            @ApiParam("备注") @RequestParam(required = false) String remark) {
        
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.ADMIN.equals(currentUser.getRole())) {
            boolean success = medicineService.reduceStock(medicineId, quantity, remark);
            if (success) {
                return Result.success(null, "药品出库成功");
            } else {
                return Result.error("药品库存不足，出库失败");
            }
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("获取药品库存统计")
    @GetMapping("/medicines/statistics")
    public Result<Map<String, Object>> getMedicineStatistics() {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.ADMIN.equals(currentUser.getRole())) {
            Map<String, Object> statistics = medicineService.getMedicineStatistics();
            return Result.success(statistics);
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("获取药品库存预警")
    @GetMapping("/medicines/warning")
    public Result<Map<String, Object>> getMedicineWarning() {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            Map<String, Object> warning = medicineService.checkStockWarning();
            return Result.success(warning);
        }
        
        return Result.error("权限不足");
    }

    // ==================== 病房信息管理 ====================
    
    @ApiOperation("获取病房列表")
    @GetMapping("/wards")
    public Result<List<Ward>> getWards(
            @ApiParam("搜索关键词") @RequestParam(required = false) String keyword,
            @ApiParam("科室ID") @RequestParam(required = false) Long departmentId,
            @ApiParam("病房类型") @RequestParam(required = false) Integer type,
            @ApiParam("楼层") @RequestParam(required = false) Integer floor) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            List<Ward> wards = wardService.getWards(keyword, departmentId, type, floor);
            return Result.success(wards);
        }
        
        return Result.error("权限不足");
    }

    @ApiOperation("获取病房详情")
    @GetMapping("/ward/{wardId}")
    public Result<Ward> getWardDetail(@PathVariable Long wardId) {
        User currentUser = UserContext.getCurrentUser();
        if (UserRole.DOCTOR.equals(currentUser.getRole()) || 
            UserRole.ADMIN.equals(currentUser.getRole())) {
            Ward ward = wardService.getById(wardId);
            return Result.success(ward);
        }
        
        return Result.error("权限不足");
    }

    // ==================== 工具方法 ====================
    
    /**
     * 检查当前用户是否为医生或管理员
     */
    private boolean isDoctorOrAdmin() {
        User currentUser = UserContext.getCurrentUser();
        return UserRole.DOCTOR.equals(currentUser.getRole()) || 
               UserRole.ADMIN.equals(currentUser.getRole());
    }

    // ==================== 公告管理 ====================
    
    @ApiOperation("获取公告列表")
    @GetMapping("/announcements")
    public Result<Map<String, Object>> getAnnouncements(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "20") Integer size,
            @ApiParam("关键词") @RequestParam(required = false) String keyword,
            @ApiParam("公告类型") @RequestParam(required = false) String type,
            @ApiParam("状态") @RequestParam(required = false) Integer status,
            @ApiParam("优先级") @RequestParam(required = false) String priority) {
        
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        // if (!isDoctorOrAdmin()) {
        //     return Result.error("权限不足");
        // }
        
        try {
            QueryWrapper<Announcement> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("deleted", 0);
            
            // 根据用户角色过滤公告
            String userRole = getUserRoleString(currentUser.getRole());
            if (userRole != null) {
                queryWrapper.and(wrapper -> wrapper
                    .like("target_audience", userRole)
                    .or()
                    .like("target_audience", "admin") // 管理员公告对所有人可见
                );
            }
            
            // 搜索条件
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.and(wrapper -> wrapper
                    .like("title", keyword)
                    .or()
                    .like("content", keyword)
                );
            }
            
            if (type != null && !type.trim().isEmpty()) {
                queryWrapper.eq("type", type);
            }
            
            if (status != null) {
                queryWrapper.eq("status", status);
            } else {
                // 默认只显示已发布的公告
                queryWrapper.eq("status", 1);
            }
            
            if (priority != null && !priority.trim().isEmpty()) {
                queryWrapper.eq("priority", priority);
            }
            
            // 排序：置顶优先，然后按发布时间倒序
            queryWrapper.orderByDesc("is_top", "publish_time");
            
            Page<Announcement> pageInfo = new Page<>(page, size);
            Page<Announcement> result = announcementMapper.selectPage(pageInfo, queryWrapper);
            
            // 处理返回数据
            List<Announcement> announcements = result.getRecords();
            for (Announcement announcement : announcements) {
                processAnnouncementData(announcement);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("list", announcements);
            response.put("total", result.getTotal());
            response.put("page", page);
            response.put("size", size);
            response.put("pages", result.getPages());
            
            return Result.success(response);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取公告列表失败: " + e.getMessage());
        }
    }
    
    @ApiOperation("获取公告详情")
    @GetMapping("/announcement/{announcementId}")
    public Result<Announcement> getAnnouncementDetail(@PathVariable Long announcementId) {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        // if (!isDoctorOrAdmin()) {
        //     return Result.error("权限不足");
        // }
        
        try {
            Announcement announcement = announcementMapper.selectById(announcementId);
            if (announcement == null) {
                return Result.error("公告不存在");
            }
            
            // 增加查看次数
            announcementMapper.incrementViewCount(announcementId);
            
            // 处理数据
            processAnnouncementData(announcement);
            
            return Result.success(announcement);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取公告详情失败: " + e.getMessage());
        }
    }
    
    @ApiOperation("标记公告已读")
    @PutMapping("/announcement/{announcementId}/read")
    public Result<Void> markAnnouncementAsRead(@PathVariable Long announcementId) {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        if (!isDoctorOrAdmin()) {
            return Result.error("权限不足");
        }
        
        try {
            // 增加阅读次数
            announcementMapper.incrementReadCount(announcementId);
            return Result.success(null, "标记已读成功");
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("标记已读失败: " + e.getMessage());
        }
    }

    // ==================== 管理员专用公告管理接口 ====================
    
    @ApiOperation("获取公告列表（管理员）")
    @GetMapping("/admin/announcements")
    public Result<Map<String, Object>> getAnnouncementsForAdmin(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "20") Integer size,
            @ApiParam("关键词") @RequestParam(required = false) String keyword,
            @ApiParam("公告类型") @RequestParam(required = false) String type,
            @ApiParam("状态") @RequestParam(required = false) Integer status,
            @ApiParam("优先级") @RequestParam(required = false) String priority) {
        
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        if (!UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        try {
            QueryWrapper<Announcement> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("deleted", 0);
            
            // 搜索条件
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.and(wrapper -> wrapper
                    .like("title", keyword)
                    .or()
                    .like("content", keyword)
                );
            }
            
            if (type != null && !type.trim().isEmpty()) {
                queryWrapper.eq("type", type);
            }
            
            if (status != null) {
                queryWrapper.eq("status", status);
            }
            
            if (priority != null && !priority.trim().isEmpty()) {
                queryWrapper.eq("priority", priority);
            }
            
            // 排序：置顶优先，然后按创建时间倒序
            queryWrapper.orderByDesc("is_top", "create_time");
            
            Page<Announcement> pageInfo = new Page<>(page, size);
            Page<Announcement> result = announcementMapper.selectPage(pageInfo, queryWrapper);
            
            // 处理返回数据
            List<Announcement> announcements = result.getRecords();
            for (Announcement announcement : announcements) {
                processAnnouncementData(announcement);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("list", announcements);
            response.put("total", result.getTotal());
            response.put("page", page);
            response.put("size", size);
            response.put("pages", result.getPages());
            
            return Result.success(response);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取公告列表失败: " + e.getMessage());
        }
    }
    
    @ApiOperation("发布公告")
    @PostMapping("/admin/announcement")
    public Result<Void> createAnnouncement(@Validated @RequestBody Announcement announcement) {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        if (!UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足，仅管理员可发布公告");
        }
        
        try {
            // 设置发布人信息
            announcement.setPublisherId(currentUser.getId());
            announcement.setPublisherName(currentUser.getName());
            
            // 设置默认值
            if (announcement.getPublishTime() == null) {
                announcement.setPublishTime(LocalDateTime.now());
            }
            if (announcement.getStatus() == null) {
                announcement.setStatus(1); // 默认已发布
            }
            if (announcement.getIsTop() == null) {
                announcement.setIsTop(0); // 默认不置顶
            }
            if (announcement.getViewCount() == null) {
                announcement.setViewCount(0);
            }
            if (announcement.getReadCount() == null) {
                announcement.setReadCount(0);
            }
            
            announcement.setCreateTime(LocalDateTime.now());
            announcement.setUpdateTime(LocalDateTime.now());
            announcement.setDeleted(0);
            
            int result = announcementMapper.insert(announcement);
            if (result > 0) {
                return Result.success(null, "公告发布成功");
            } else {
                return Result.error("公告发布失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("公告发布失败: " + e.getMessage());
        }
    }
    
    @ApiOperation("更新公告")
    @PutMapping("/admin/announcement")
    public Result<Void> updateAnnouncement(@Validated @RequestBody Announcement announcement) {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        if (!UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足，仅管理员可更新公告");
        }
        
        try {
            announcement.setUpdateTime(LocalDateTime.now());
            
            int result = announcementMapper.updateById(announcement);
            if (result > 0) {
                return Result.success(null, "公告更新成功");
            } else {
                return Result.error("公告更新失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("公告更新失败: " + e.getMessage());
        }
    }
    
    @ApiOperation("删除公告")
    @DeleteMapping("/admin/announcement/{announcementId}")
    public Result<Void> deleteAnnouncement(@PathVariable Long announcementId) {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        if (!UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足，仅管理员可删除公告");
        }
        
        try {
            int result = announcementMapper.deleteById(announcementId);
            if (result > 0) {
                return Result.success(null, "公告删除成功");
            } else {
                return Result.error("公告删除失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("公告删除失败: " + e.getMessage());
        }
    }
    
    @ApiOperation("置顶公告")
    @PutMapping("/admin/announcement/{announcementId}/top")
    public Result<Void> topAnnouncement(
            @PathVariable Long announcementId,
            @RequestBody Map<String, Object> request) {
        
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        if (!UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足，仅管理员可置顶公告");
        }
        
        try {
            Boolean isTop = (Boolean) request.get("isTop");
            String topUntilStr = (String) request.get("topUntil");
            
            Announcement announcement = new Announcement();
            announcement.setId(announcementId);
            announcement.setIsTop(isTop != null && isTop ? 1 : 0);
            
            if (topUntilStr != null && !topUntilStr.isEmpty()) {
                announcement.setTopUntil(LocalDateTime.parse(topUntilStr));
            }
            
            announcement.setUpdateTime(LocalDateTime.now());
            
            int result = announcementMapper.updateById(announcement);
            if (result > 0) {
                return Result.success(null, isTop != null && isTop ? "置顶成功" : "取消置顶成功");
            } else {
                return Result.error("操作失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("操作失败: " + e.getMessage());
        }
    }
    
    @ApiOperation("撤回公告")
    @PutMapping("/admin/announcement/{announcementId}/withdraw")
    public Result<Void> withdrawAnnouncement(
            @PathVariable Long announcementId,
            @RequestBody Map<String, Object> request) {
        
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        if (!UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足，仅管理员可撤回公告");
        }
        
        try {
            String reason = (String) request.get("reason");
            
            Announcement announcement = new Announcement();
            announcement.setId(announcementId);
            announcement.setStatus(2); // 已撤回
            announcement.setWithdrawReason(reason);
            announcement.setWithdrawTime(LocalDateTime.now());
            announcement.setUpdateTime(LocalDateTime.now());
            
            int result = announcementMapper.updateById(announcement);
            if (result > 0) {
                return Result.success(null, "公告撤回成功");
            } else {
                return Result.error("公告撤回失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("公告撤回失败: " + e.getMessage());
        }
    }
    
    @ApiOperation("批量操作公告")
    @PutMapping("/admin/announcements/batch")
    public Result<Void> batchOperateAnnouncements(@RequestBody Map<String, Object> request) {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        if (!UserRole.ADMIN.equals(currentUser.getRole())) {
            return Result.error("权限不足，仅管理员可批量操作公告");
        }
        
        try {
            @SuppressWarnings("unchecked")
            List<Integer> announcementIds = (List<Integer>) request.get("announcementIds");
            String action = (String) request.get("action");
            String reason = (String) request.get("reason");
            
            if (announcementIds == null || announcementIds.isEmpty()) {
                return Result.error("请选择要操作的公告");
            }
            
            String ids = announcementIds.stream()
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));
            
            if ("delete".equals(action)) {
                // 批量删除
                for (Integer id : announcementIds) {
                    announcementMapper.deleteById(id.longValue());
                }
                return Result.success(null, "批量删除成功");
            } else if ("withdraw".equals(action)) {
                // 批量撤回
                announcementMapper.batchUpdateStatus(ids, 2);
                return Result.success(null, "批量撤回成功");
            } else {
                return Result.error("不支持的操作类型");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量操作失败: " + e.getMessage());
        }
    }

    // ==================== 辅助方法 ====================
    
    /**
     * 获取用户角色字符串
     */
    private String getUserRoleString(Integer role) {
        if (UserRole.DOCTOR.equals(role)) {
            return "doctor";
        } else if (UserRole.ADMIN.equals(role)) {
            return "admin";
        } else if (UserRole.PATIENT.equals(role)) {
            return "patient";
        }
        return null;
    }
    
    /**
     * 处理公告数据
     */
    private void processAnnouncementData(Announcement announcement) {
        try {
            // 计算阅读率
            if (announcement.getViewCount() != null && announcement.getViewCount() > 0) {
                double readRate = (double) (announcement.getReadCount() != null ? announcement.getReadCount() : 0) 
                                / announcement.getViewCount() * 100;
                announcement.setReadRate(Math.round(readRate * 100.0) / 100.0);
            } else {
                announcement.setReadRate(0.0);
            }
            
            // 设置类型名称
            announcement.setTypeName(getTypeNameByType(announcement.getType()));
            
            // 设置优先级名称
            announcement.setPriorityName(getPriorityNameByPriority(announcement.getPriority()));
            
            // 设置状态名称
            announcement.setStatusName(getStatusNameByStatus(announcement.getStatus()));
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private String getTypeNameByType(String type) {
        if (type == null) return "未知";
        switch (type) {
            case "system": return "系统公告";
            case "department": return "科室通知";
            case "emergency": return "紧急通知";
            case "maintenance": return "维护通知";
            case "policy": return "政策通知";
            default: return "未知";
        }
    }
    
    private String getPriorityNameByPriority(String priority) {
        if (priority == null) return "普通";
        switch (priority) {
            case "low": return "低";
            case "normal": return "普通";
            case "high": return "高";
            case "urgent": return "紧急";
            default: return "普通";
        }
    }
    
    private String getStatusNameByStatus(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "草稿";
            case 1: return "已发布";
            case 2: return "已撤回";
            case 3: return "已过期";
            default: return "未知";
        }
    }
} 